# -*- coding:utf-8 -*-
from flask import current_app
from qiniu import Auth, put_data

from info.libs import constants


def storage(localfile):
    """
    七牛云上传文件
    :param localfile: 要上传文件的本地路径
    """
    if localfile:
        try:
            # 构建鉴权对象
            q = Auth(constants.QINIUYUN_ACCESS_KEY, constants.QINIUYUN_SECRET_KEY)
            # 要上传的空间
            bucket_name = constants.QINIUYUN_BUCKET_NAME
            # 上传后保存的文件名
            key = None
            # 生成上传 Token，可以指定过期时间等
            token = q.upload_token(bucket_name, key)

            ret, info = put_data(token, key, localfile)
        except Exception as e:
            current_app.logger.error(e)
            return

        if info.status_code != 200:
            current_app.logger.error(f"文件上传失败\n七牛云响应：{ret}")
            return
        return ret.get("key")
